#include <header.h>

void my_read(int file_fd, char *buf, ssize_t len){

   ssize_t size = 0;
   while(size < len){
       ssize_t ret = read(file_fd, buf+size, len-size);

       size += ret;
   }
}
int main(){

   int file_fd = open("1.txt", O_WRONLY);
   int num = 1;
   write(file_fd, &num, sizeof(int));
   close(file_fd);

   while(1){

       file_fd = open("1.txt", O_RDONLY);
       num = 0;
       read(file_fd, &num, sizeof(int));
       close(file_fd);

       if(num == 1){
           // 读标准输入: 写文件
           char buf[100] = {0};
           read(STDIN_FILENO, buf, sizeof(buf));

           int file_fd = open("1.txt", O_WRONLY);
           num = 0;
           write(file_fd, &num, sizeof(int));
           write(file_fd, buf, sizeof(buf));
           close(file_fd);
           file_fd = open("1.txt", O_WRONLY);
           num = 2;
           write(file_fd, &num, sizeof(int));
           close(file_fd);
       }else if(num == 4){
           // 读文件数据:打印
           file_fd = open("1.txt", O_RDONLY);
           num = 0;
           read(file_fd, &num, sizeof(int));
           char buf[100] = {0};
           my_read(file_fd, buf, sizeof(buf));
           printf("%s \n", buf);
           close(file_fd);

           int file_fd = open("1.txt", O_WRONLY);
           num = 1;
           write(file_fd, &num, sizeof(int));
       }
   }

   return 0;
}
